/*
 * @Description: 封装axios请求
 * @version:
 * @Author: m
 * @LastEditors: m
 */

import axios from "axios";
import Qs from "qs";
// import { Toast } from "vant";
import { getToken, removeToken } from "@/utils/auth";
import global_url from "@/utils/global";
import router from "../router";

console.log(global_url);
const service = axios.create({
  baseURL: global_url.httpUrl,
  timeout: 60 * 1000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
  },
  withCredentials: true,
});

// console.log(process.env.VUE_APP_TITLE)
// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    config.data = Qs.stringify(config.data);
    // config.data = config.data + "&token=" + getToken();
    // console.log(getToken());
    if (!getToken()) {
      console.log("");
    } else {
      config.headers.OAUTH_BEARER_TOKEN = getToken().token;
    }

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

//添加响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code != 200) {
      if (res.code == 300) {
        // Toast.fail(res.message);
        this.$message.success();
        return res;
      } else if (res.code == 301) {
        removeToken();
        router.push("/login");
        return res;
      } else if (res.code == 500) {
        // Toast.fail("服务器异常!");
        return Promise.reject();
      } else if (res.code == 400) {
        // Toast.fail("请求错误!");
        return Promise.reject();
      } else {
        return res;
      }
    } else {
      return res;
    }
  },
  (error) => {
    // Toast.fail("网络连接错误");
    return Promise.reject(error);
  }
);

export default service;
